package cake.dao.impl;

import java.awt.dnd.DnDConstants;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import cake.dao.UserDao;
import cake.entity.User;

public class UserDaoImpl implements UserDao{

	private JdbcTemplate db= new JdbcTemplate();
	
	private class UserMapper implements RowMapper<User>{

		public User mapRow(ResultSet rs) throws SQLException {
			return new User(rs.getInt("id"), rs.getString("userName"), rs.getString("passWord"), rs.getString("email"), rs.getBoolean("status"));
		}
		
	}
	
	public boolean addUser(User user) {
		return db.update("insert into user(username,password,email,status) values(?,?,?,?)", user.getUserName(),user.getPassWord(),user.getEmail(),user.isStatus());
	}

	public User checkLoginUser(String userName, String passWord) {
		return db.queryOne("select * from user where username=? and password=?", new UserMapper(), userName,passWord);
	}

	public boolean checkUserName(String userName) {
		return db.query("select * from user where username=?", new UserMapper(), userName).size()>0;
	}

	public boolean updateUserStatus(User user) {
		return db.update("update user set status=? where username=? ", user.isStatus(),user.getUserName());
	}

	public User fetchUserByUserName(String username) {
		return db.queryOne("select * from user where username=? ", new UserMapper(), username);
	}
	
	@Override
	public List<User> getAll() {
		return db.query("select * from user", new UserMapper());
	}

	@Override
	public List<User> getUsersByKeyWord(String keyWord) {
		return db.query("select * from user where username like ?", new UserMapper(), "%"+keyWord+"%");
	}
	
	public User getUserByUid(int uid) {
		String sql="select * from User where id=?";
		return db.queryOne(sql, new UserMapper(),uid);
	}
	
}
